define(function(require, exports) {
	require("js/jquery-2.1.4.js");
	var framework = require("manage/js/framework.js");
	require('manage/js/choiceTime.js');
	//require("${appPath}/js/ajaxfileupload.js");
	framework.setCurrentMenu("PAGE_001");
	checkIsLogin();
	
	search();
	
	// 检查用户是否登陆
	function checkIsLogin(){
		var admin = sessionStorage.getItem("admin");
	    $("#userNU .userC").find("dt").html(admin);
	    $("#userNU .userC").find("dt").attr("title",admin);
		if(admin==null || admin==""){
			window.location.href="http://localhost:8080/erhuogo/manage/login.html";
		}
	}
	// 查找函数
	function search() {
		var page = getHashPage();
		if (page == null) {
			page = 1;
		}
		searchHandler(page);
	}

	function searchHandler(page) {
		page = parseInt(page);
		window.location.hash = "#" + page;
		clearTable();
		initTable(page);
	}

	function clearTable() {
		$(".content .commonTb tr:gt(0)").detach();
		$(".content .paginator span").detach();
	}
	
	function GetQueryString(name) { 
		  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
		  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
		  var context = ""; 
		  if (r != null) 
		     context = r[2]; 
		  reg = null; 
		  r = null; 
		  return context == null || context == "" || context == "undefined" ? "" : context; 
	}

	// 初始化列表
	function initTable(page) {
		framework.showLoading();
		/*
		 * var rows = Math.floor(($(window).height() - $('.topNav').height() -
		 * $('.content .noBorderB').height() - $('.content .searchD').height() -
		 * $('.content .commonTb tr:eq(0)').height() - 100 ) / 50); rows = rows <=
		 * 0 ? 1 : rows;
		 */
		var rows = 20;
		var oneCategoryId = GetQueryString("oneCategoryId");
		var twoCategoryId = GetQueryString("twoCategoryId");
		var id = $("#searchId").val();
		var name = $("#searchName").val();
		var code = $("#searchCode").val();
		var date = $("#datePicker").val();
		var startDate = $('input[id="startDate"]').val();
		var endDate = $('input[id="endDate"]').val();
		
		$.ajax({
			url:"threeCategory_listPage.action",
			type:"get",
			dataType:"json",
			data:{
				"page":page,
				"rows":rows,
				"id":id,
				"name":name,
				"code":code,
				"oneCategoryId":oneCategoryId,
				"twoCategoryId":twoCategoryId,
				"startDate" : startDate,
				"endDate" : endDate
			},
			success:function(data){
				if (data.data != null && data.data.rows != null) {
					for (var index = 0; index < data.data.rows.length; index++) {
						initTableRow(data.data.rows[index], index + 1);
					}
					if (data.data.records <= rows) {
						$('.paginator').css("display", "none");
					} else {
						$('.paginator').css("display", "");
					}
					initFooder(page, rows, data.data.records);
				}
				framework.hideLoading();
			}
		});
	}
	
	// 初始化表行
	function initTableRow(rowObject, index) {
		var clazz = "";
		if (index % 2 == 0) {
			clazz = "alt";
		}
		var row = $("<tr/>");

		var id = rowObject.id;
		var code = rowObject.code;
		var name = rowObject.name;
		var desc = rowObject.desc;
		var status = rowObject.status;
		var createTime = rowObject.createTime;
		var alterTime = rowObject.alterTime;
		
		var _status = "";
		if (status=="0"){
			_status = "启用";
		}else if(status=="1"){
			_status = "屏蔽";
		}
		
		var tdDiv = "";
		tdDiv += '<div class="editM1" title="编辑"><a href="javascript:void(0);">编辑</a></div>';
		if(status=="0"){
			tdDiv += '<div class="editM2" title="屏蔽"><a href="javascript:void(0);">屏蔽</a></div>';
		}else if(status=="1"){
			tdDiv += '<div class="editM2" title="启用"><a href="javascript:void(0);">启用</a></div>';
		}
		row.append('<td class="operateTd_d" style="line-height: 28px;" id="_operateTd_'
				+ index + '">' + tdDiv + '</td>');

		row.append('<td title="'+ id +'" style="text-align:center">'+ id +'</>');
		row.append('<td title="'+ code +'" style="text-align:center">'+ code +'</>');
		row.append('<td title="'+ name +'" style="text-align:center">'+ name +'</>');
		row.append('<td title="'+ desc +'" style="text-align:center">'+ desc +'</>');
		row.append('<td title="'+ _status +'" style="text-align:center">'+ _status +'</>');
		row.append('<td title="'+ createTime +'" style="text-align:center">'+ createTime +'</>');
		row.append('<td title="'+ alterTime +'" style="text-align:center">'+ alterTime +'</>');
		row.addClass(clazz);
		row.hover(function() {
			row.removeClass(clazz);
			row.addClass("over");
		}, function() {
			row.removeClass("over");
			row.addClass(clazz);
		});
		row.attr("threeCategotyId", id);
		$(".content .commonTb").append(row);
		
		// 编辑点击事件
		$("#_operateTd_" + index + " .editM1").click(function() {
			initEidit();
			$.ajax({
				url:"threeCategory_findById.action",
				type:"get",
				dataType:"json",
				data:{"id":id},
				success:function(data){
					if(data.result=="SUCCESS"){
						$(".maskbg").hide();
						edit(data.data);
					}else{
						framework.error(data.message);
					}
				}
			});
		});

	    function IsNum(num){
	    	var reNum=/^\d*$/;
	    	return(reNum.test(num));
		}

		// 屏蔽点击事件
		$("#_operateTd_" + index + " .editM2").click(function() {
			var transStatus = "";
			var _operate = "";
			if(status=="0"){
				transStatus = 1;
				_operate = "屏蔽";
			}else if(status=="1"){
				transStatus = 0;
				_operate = "启用";
			}
			framework.confirmss("确定"+_operate+"三级分类:["+name+"]?",
			function(){
				$.ajax({
					url:"threeCategory_updateStatusById.action",
					type:"get",
					data:{"id":id,"status":transStatus},
					success:function(data){
						if(data.result=="SUCCESS"){
							search();
							framework.hint(_operate+"成功");
						}else{
							search();
							framework.hint(_operate+"失败");
						}
					}
				})
			},function(){
				
			})
		});
		
	}

	// 初始化脚
	// 参数： 第几页 行数 数量
	function initFooder(page, rows, count) {
		$('.content .paginator').append(
				'<span class="prev">上一页</span> '
						+ ' <span class="next">下一页</span>'
						+ '<span class="right">共</span> '
						+ '<div class="clear"></div>');
		var pageCount = Math.ceil(count / rows);
		var spanArray = new Array();
		spanArray.push(page);
		var i = 1;
		var mix = 5 > pageCount ? pageCount : 5;
		while (spanArray.length < mix) {
			if (page + i <= pageCount) {
				spanArray.push(page + i);
			}
			if (page - i > 0) {
				spanArray.unshift(page - i);
			}
			i++;
		}
		var firstCurrent = '';
		var lastCurrent = '';
		if (page == pageCount) {
			lastCurrent = 'class="current"';
		}
		if (page == 1) {
			firstCurrent = 'class="current"';
		}
		if (page <= pageCount - 3) {
			$('.content .paginator .prev:last').after(
					$('<span ' + lastCurrent + '></span>').append(
							initFooderPage(pageCount, pageCount))).after(
					$('<span></span>').append('...'));
		} else {
			$('.content .paginator .prev:last').after(
					$('<span ' + lastCurrent + '></span>').append(
							initFooderPage(pageCount, pageCount)));
		}
		for (var index = spanArray.length - 2; index >= 1; index--) {
			if (spanArray[index] == page) {
				$('.content .paginator .prev:last').after(
						$('<span class="current">' + page + '</span>'));
			} else {
				$('.content .paginator .prev:last').after(
						$('<span></span>').append(
								initFooderPage(spanArray[index],
										spanArray[index])));
			}
		}
		if (page > 3) {
			$('.content .paginator .prev:last').after(
					$('<span ' + firstCurrent + '></span>').append('...'))
					.after($('<span></span>').append(initFooderPage(1, 1)));
		} else {
			$('.content .paginator .prev:last').after(
					$('<span ' + firstCurrent + '></span>').append(
							initFooderPage(1, 1)));
		}

		if (page != 1) {
			$('.content .paginator .prev:first').html(
					initFooderPage(page - 1, '上一页'));
		}

		if (page != pageCount) {
			$('.content .paginator .next:first').html(
					initFooderPage(page + 1, '下一页'));
		}
		$('.content .paginator a').click(function() {
			searchHandler(parseInt($(this).attr('page')));
		});

		$('.content .paginator .right:last')
				.before(
						$('<span class="leftbd20"><img id="pgSubmit" src="./manage/images/footer_submit.png"></span>'))
				.before($('<span class="leftbd7"></span>').append('页'))
				.before(
						$('<span class="leftbd7"><input type="text" id="pgnum" class="text40" value="'
								+ page + '"></span>')).before(
						$('<span class="leftbd20"></span>').append('转到第'))
				.before($('<span class="leftbd2"></span>').append('条')).before(
						$('<span class="pageNum"></span>').append(count));

		$('#pgSubmit').click(function() {
			var pgnum = parseInt($('#pgnum').val());
			if (pgnum >= 1 && pgnum <= pageCount) {
				searchHandler(pgnum);
			} else {
				framework.hint("超出页码范围，一共" + pageCount + "页");
			}
		});
	}

	// 初始化点击脚的内容
	function initFooderPage(page, name) {
		var st = '<a href="javascript:void(0);" page=' + page + '>' + name
				+ '</a>';
		return st;
	}

	function longTrans2Date(time) {
		if (time == null || time == "")
			return "";
		var newTime = new Date(time);
		return newTime.Format("yyyy-MM-dd hh:mm:ss");
	}

	exports.searchList = function() {
		search();
	}

	$(window).bind('hashchange',function(e) {
		if ($('.content .paginator .current').html() == null) {
			return;
		}
		var hashPage = getHashPage();
		if (hashPage == null) {
			return;
		}
		if ($('.content .paginator .current').html()&& $('.content .paginator .current').html() != hashPage) {
			searchHandler(hashPage);
		}
	});

	function getHashPage() {
		var page = null;
		if (window.location.hash) {
			page = window.location.hash;
			if (page.indexOf("#") != -1) {
				page = page.substring(1);
			}
		}
		return page;
	}
	
	//搜索
	$("#searchListButton").click(function(){
		clearTable();
		searchHandler(1);
	});

	//添加三级分类
	$("#createAppBtn").click(function() {
		initEidit();
	});
	
	//清除搜索条件
	$("#clearBar").click(function(){
		$("#searchName").val("");
		$("#searchId").val("");
		$("#searchCode").val("");
		$("#startDate").val("");
		$("#endDate").val("");
		$('#datePicker').data('dateRangePicker').clear();
	});
	
	//保存信息
	$("#saveThreeCategory").click(function(){
		var oneCategoryId = GetQueryString("oneCategoryId");
		var twoCategoryId = GetQueryString("twoCategoryId");
		saveThreeCategory(oneCategoryId,twoCategoryId);
	});
	
	//取消保存
	$("#cancelSave").click(function(){
		$("#threeCategory").hide();
		$(".maskbg").hide();
	});
	
	function initEidit(){
		$("#threeCategory").show();
		$(".maskbg").show();
		$("#threeCategoryId").val("");
		$("#code").val("");
		$("#name").val("");
		$("#summary").val("");
	}
	
	function saveThreeCategory(oneCategoryId,twoCategoryId){
		var id = $("#threeCategoryId").val();
		var code = $.trim($("#code").val());
		var name = $.trim($("#name").val());
		var summary = $.trim($("#summary").val());
		if(code==""){
			framework.hint("请输入编码");
			return ;
		}else{
			if(code.length>10){
				framework.hint("编码不能超过10字符");
				return ;
			}
		}
		if(name==""){
			framework.hint("请输入三级分类名称");
			return ;
		}else{
			if(name.length>10){
				framework.hint("三级分类名称不能超过10字符");
				return ;
			}
		}
		if(summary==""){
			framework.hint("请输入简介");
			return ;
		}else{
			if(summary.length>120){
				framework.hint("简介不能超过120字符");
				return ;
			}
		}
		var param = {"id":id,"code":code,"name":name,"desc":summary,"oneCategoryId":oneCategoryId,"twoCategoryId":twoCategoryId}
		$.ajax({
			url:"threeCategory_saveThreeCategory.action",
			type:"post",
			data:param,
			success:function(data){
				if(data.result=="SUCCESS"){
					$("#threeCategory").hide();
					$(".maskbg").hide();
					if(id!=""){
						framework.hint("修改成功");
					}else{
						framework.hint("添加成功");
					}
					search();
				}else{
					$("#threeCategory").hide();
					$(".maskbg").hide();
					if(id!=""){
						framework.hint("修改失败");
					}else{
						framework.error("添加失败");
					}
					search();
				}
			}
		});
	}
	
	function edit(threeCategory){
		$("#threeCategory").show();
		$(".maskbg").show();
		$("#threeCategoryId").val(threeCategory.id);
		$("#code").val(threeCategory.code);
		$("#name").val(threeCategory.name);
		$("#summary").val(threeCategory.desc);
	}
	
});
